import axios from "axios";
axios.defaults.baseURL = "http://59.110.123.33:3000";
axios.interceptors.request.use(function (config) {
    const accessToken = localStorage.getItem("accessToken");//本地获取访问令牌
    if (accessToken) {//将访问令牌添加到请求头中
        config.headers["Authorization"] = 'Bearer ' + accessToken
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    return response;
}, async (error) => {
    console.log(error.response.status);
    
    if (error.response.status === 401) {//若收到401,说明还未登录
        alert('还未登录，请先登录！')
        localStorage.clear()
        window.location.href = '/login';
        return false
    }
    if (error.response.status === 403) {//接收到403,说明访问令牌过期
        try {
            const { data: { newAccessToken } } = await axios.post('refreshtoken', {
                refreshToken: localStorage.getItem('refreshToken'),
            });//携带刷新令牌,访问后端刷新访问令牌接口
            localStorage.setItem('accessToken', newAccessToken);//保存刷新后的访问令牌与刷新令牌
            console.log('token刷新辣');
            
            // 重新发送原始请求
            return axios(error.response.config)
        } catch (err) {
            //若出错，则清除所有缓存，跳转到登录页
            localStorage.clear()
            window.location.href = '/login';
            return Promise.reject(error);
        }

    }
    return Promise.reject(error);
});
export default axios;